package com.mazaiting.auth.security.core.userdetails.user;

import com.mazaiting.auth.enums.AuthenticationIdentityEnum;
import com.mazaiting.auth.enums.RefreshTypeEnum;
import com.mazaiting.auth.security.core.userdetails.base.BaseUserDetailsService;
import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.manager.api.IUserFeignClient;
import com.mazaiting.manager.dto.UserAuthDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 系统用户体系业务类
 */
@Slf4j
@Service("sysUserDetailsService")
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl extends BaseUserDetailsService {

    private final IUserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取系统用户详细信息
        Result<UserAuthDTO> result = userFeignClient.getUserByUsername(username);
        // 获取用户
        SysUserDetails sysUserDetails = getSysUserDetails(result);
        // 设置认证标识
        sysUserDetails.setAuthenticationIdentity(AuthenticationIdentityEnum.USERNAME.getValue());
        // 设置刷新类型
        sysUserDetails.setRefreshType(RefreshTypeEnum.CLIENT_MANAGER.name());
        return sysUserDetails;
    }

    /**
     * 手机号码认证方式
     *
     * @param mobile 手机号
     * @return 用户详情服务
     */
    public UserDetails loadUserByMobile(String mobile) {
        // 获取用户信息
        Result<UserAuthDTO> result = userFeignClient.getUserByMobile(mobile);
        SysUserDetails userDetails = getSysUserDetails(result);
        // 认证身份标识:mobile
        userDetails.setAuthenticationIdentity(AuthenticationIdentityEnum.MOBILE.getValue());
        // 设置刷新类型
        userDetails.setRefreshType(RefreshTypeEnum.CLIENT_MANAGER.name());
        return userDetails;
    }

    /**
     * 获取用户详情信息
     * @param result 远程调用结果
     * @return 系统用户详情
     */
    @NotNull
    private SysUserDetails getSysUserDetails(Result<UserAuthDTO> result) {
        SysUserDetails userDetails = null;
        // 获取用户
        if (result.check()) {
            UserAuthDTO userAuthDTO = result.getData();
            if (Objects.nonNull(userAuthDTO)) {
                userDetails = new SysUserDetails(userAuthDTO);
            }
        }
        // 判断用户详情是否为空
        if (Objects.isNull(userDetails)) {
            throw new UsernameNotFoundException(result.getMsg());
        }
        checkUserDetails(userDetails);
        return userDetails;
    }

}
